package com.xnx3.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xnx3.j2ee.util.ApplicationPropertiesUtil;
import com.xnx3.kefu.entity.ChatgptVO;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class ChatGptUtils {
    public static String getResultByText(String text,String model,String apaas) {
        Map<String, String> header = new HashMap<>();
        //如果是科大讯飞，需要传入header数据
        Object kdxf = ApplicationPropertiesUtil.getProperty("kdxf.header");
        if(kdxf != null) {
            header.put("Authorization",kdxf.toString());
        }
        Map<String, String> querys = new HashMap<>();
        ChatgptVO chatgptVO=new ChatgptVO();
        Map tempMessage=new HashMap();
        tempMessage.put("role","user");
        tempMessage.put("content","请用中文回答以下问题："+text);
        LinkedList list=new LinkedList();
        list.add(tempMessage);
        chatgptVO.setMessages(list);
        chatgptVO.setModel(model);
        chatgptVO.setStream(false);
        chatgptVO.setMax_tokens(1024);
        System.out.println("vo:====>"+ JSON.toJSONString(chatgptVO));
        Object url = ApplicationPropertiesUtil.getProperty("chatgpt.url");
        if(url == null) {
            throw new BusinessException("yml配置文件有误，请查询配置文件！");
        }
        //请求发起时间
        String ret = HttpClientUtil.doPost(url.toString(), "", header, querys,
                JSON.toJSONString(chatgptVO));
        System.out.println(ret);
        if("bd".equals(apaas)){
            if (StringUtils.isNotBlank(ret)) {
                JSONObject obj = JSONObject.parseObject(ret);
                JSONObject resMessage = obj.getJSONObject("message");
                if(resMessage!=null){
                    String content = resMessage.getString("content");
                    System.out.println("content:======>"+content);
                    return content;
                }
            }
        }else if("kdxf".equals(apaas)){
            if (StringUtils.isNotBlank(ret)) {
                JSONObject obj = JSONObject.parseObject(ret);
                JSONArray resMessage = obj.getJSONArray("choices");
                if(resMessage!=null){
                    JSONObject jo = resMessage.getJSONObject(0);
                    JSONObject message = jo.getJSONObject("message");
                    System.out.println("content:======>"+message);
                    String content = message.getString("content");
                    return content;
                }
            }
        }
        throw new BusinessException("查询不到结果数据，大模型平台返回："+ret);
    }
}
